﻿var BaseUrl = "";//RootUrl
var User = {
    //用户初始化
    Init: function () {
        var table = $(".dataTables").CustomForm({
            isValidate: false,
            isTable: true,
            "order": [[7, "desc"]], //默认排序
            deleteUrl: BaseUrl + "/user/Delete",
            ajaxUrl: BaseUrl + "/user/ForGrid",
            actionClick: function (target) {
                if (target.attr("event") == 1) {//角色设置
                    Role.Remote(target);
                }
                if (target.attr("event") == 2) {//权限设置
                    Permission.Remote(target, 3);
                }
                if (target.attr("event") == 3) {//角色设置
                    Group.Remote(target);
                }
            },
            "columns": [
                CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("UserId")
                , {

                    "name": "UserName",
                    "data": "UserName",
                    "title": " 用户名称",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true
                }

                , {

                    "name": "Phone",
                    "data": "Phone",
                    "title": " 电话",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                }

                , {

                    "name": "Email",
                    "data": "Email",
                    "title": " 邮箱",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                }

                , {

                    "name": "RealName",
                    "data": "RealName",
                    "title": " 真实姓名",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                }

                , CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("ApproveState", true, '审核状态')
                , CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("IsLocked", true, '是否锁定')
                , CONSTANT.DATA_TABLES.COLUMN.LASTMODIFYDATE
                , CONSTANT.DATA_TABLES.COLUMN.ACTIONBTN("UserId", BaseUrl + "/user/Edit", [
                    {
                        name: "编辑",
                        data: "UserId",
                        icon: "fa-paste",
                        url: BaseUrl + "/user/Edit",
                        cssClass: ""
                    },
                    {
                        name: "添加角色",
                        data: "UserId",
                        icon: "fa-user",

                        cssClass: ""
                    },
                    {
                        name: "添加权限",
                        data: "UserId",
                        icon: "fa-plus",

                        cssClass: ""
                    },
                    {
                        name: "添加组",
                        data: "UserId",
                        icon: "fa-group",

                        cssClass: ""
                    }
                ])
            ],
            /*
            * 向服务器传递的参数
            */
            "fnServerParams": function (data) {
                data.keyWord = $("form[datatable='tableGrid']").find("#keyWord").val();
            }
        });
    },
    ///选择用户
    Remote: function (target, relationType) {
        Notify.Remote({
            Title: "用户设置",
            remote: BaseUrl + "/user/List?t=" + Math.random() + "&resourceId=" + target.attr("id") + "&relationType=" + relationType,
            buttons: [
                { id: "close", isClose: true, Name: "关闭" }
                //{
                //    id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                //        var itemKeys = "";
                //        itemKeys = Permission.GetNodeTree(modal, ".jstree");
                //        Ajax({
                //            url: BaseUrl + "/admin/RelationUser/RelationUserSave",
                //            data: { UserId: itemKeys, keys: target.attr("id") },
                //            success: function (result) {
                //                modal.modal("hide");
                //            }
                //        });

                //        return false;
                //    }
                //}
            ],
            loaded: function (modal, id) {
                User.loadUserGrid("allUsertableGrid", modal, BaseUrl + "/User/ForGrid", target.attr("id"), relationType);
                var rltable = User.loadUserGrid("relationusertableGrid", modal, BaseUrl + "/relationUser/ForGridByResourceId", target.attr("id"), relationType);

                $("form[datatable='allUsertableGrid']").find(".btn-add").on("click", function () {
                    RelationUser.Add("#allUsertableGrid", relationType, target, function () {
                        rltable.fnPageChange(0);
                    });

                });
                $("form[datatable='relationusertableGrid']").find(".btn-remove").on("click", function () {
                    RelationUser.Remove("#relationusertableGrid", relationType, target, function () {
                        rltable.fnPageChange(0);
                    });
                });
            }
        })
    },

    //Grid初始化
    loadUserGrid: function (gridId, modal, url, id, relationType) {
        return modal.find("#" + gridId).CustomForm({
            isValidate: false,
            isTable: true,
            "order": [[1, "desc"]], //默认排序
            ajaxUrl: url,
            "columns": [
                CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("UserId")
                , {
                    "name": "UserName",
                    "data": "UserName",
                    "title": " 用户名称",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                }
                , {

                    "name": "RealName",
                    "data": "RealName",
                    "title": " 真实姓名",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                }],
            "fnServerParams": function (data) {
                data.keyWord = $("form[datatable='" + gridId + "']").find("#keyWord").val();
                data.RelationType = relationType;
                data.ResourceId = id;
            }

        });
    }
}
//角色
var Role = {
    Init: function () {
        var table = $("#tableGrid").CustomForm({
            isValidate: false,
            isTable: true,
            "order": [[5, "desc"]], //默认排序
            deleteUrl: BaseUrl + "/role/Delete",
            ajaxUrl: BaseUrl + "/role/ForGrid",
            actionClick: function (target) {
                if (target.attr("event") == 1) {//设置用户
                    User.Remote(target, 0);
                }
                if (target.attr("event") == 2) {//权限设置
                    Permission.Remote(target, 0);
                }
            },
            "columns": [
                CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("RoleId")
                , {
                    "name": "RoleKey",
                    "data": "RoleKey",
                    "title": " 角色标识",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                }
                , {
                    "name": "RoleName",
                    "data": "RoleName",
                    "title": " 角色名称",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true
                }
                , CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("IsSystem", true, "是否系统")
                , {

                    "name": "Remark",
                    "data": "Remark",
                    "title": " 备注",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                },
                CONSTANT.DATA_TABLES.COLUMN.LASTMODIFYDATE

                , CONSTANT.DATA_TABLES.COLUMN.ACTIONBTN("RoleId", BaseUrl + "/role/Edit", [
                    {
                        name: "编辑",
                        data: "RoleId",
                        icon: "fa-paste",
                        url: BaseUrl + "/role/Edit",
                        cssClass: ""
                    },
                    {
                        name: "添加用户",
                        data: "RoleId",
                        icon: "fa-user",
                        cssClass: ""
                    },
                    {
                        name: "添加权限",
                        data: "RoleId",
                        icon: "fa-plus",
                        cssClass: ""
                    }
                ])

            ],
            /*
            * 向服务器传递的参数
            */
            "fnServerParams": function (data) {
                data.keyWord = $("form[datatable='tableGrid']").find("#keyWord").val();

            }
        });
    },
    Remote: function (target) {
        Notify.Remote({
            Title: "设置角色",
            remote: BaseUrl + "/role/RoleTree?t=" + Math.random() + "&userid=" + target.attr("id"),
            buttons: [
                { id: "close", isClose: true, Name: "关闭" },
                {
                    id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                        var itemKeys = "";
                        itemKeys = Permission.GetNodeTree(modal, ".jstree");
                        Ajax({
                            url: BaseUrl + "/relationUser/relationUserSave",
                            data: { UserId: target.attr("id"), keys: itemKeys, relationType: 0 },
                            success: function (result) {
                                modal.modal("hide");
                            }
                        });
                    }
                }
            ],
            loaded: function (modal, id) {//初始化对象
                modal.find(".jstree").jstree({
                    "checkbox": {
                        "three_state": true,//父子级别级联选择
                        "tie_selection": true,
                        "keep_selected_style": false
                    },
                    "plugins": ["wholerow", "checkbox"]
                });
            }
        })
    }
}
//角色
var Group = {
    Init: function () {
        var table = $("#tableGrid").CustomForm({
            isValidate: false,
            isTable: true,
            "order": [[5, "desc"]], //默认排序
            deleteUrl: "/ORG/Group/Delete",
            ajaxUrl: "/ORG/Group/ForGrid",
            actionClick: function (target) {
                if (target.attr("event") == 1) {//设置用户
                    User.Remote(target, 1);
                }
                if (target.attr("event") == 2) {//权限设置
                    Permission.Remote(target, 1);
                }
            },
            "columns": [
                CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("GroupId")
                , {
                    "name": "GroupKey",
                    "data": "GroupKey",
                    "title": " 组标识",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                }
                , {
                    "name": "GroupName",
                    "data": "GroupName",
                    "title": " 组",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true
                }
                , CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("IsSystem", true, "是否系统")
                , {

                    "name": "Remark",
                    "data": "Remark",
                    "title": " 备注",
                    "sDefaultContent": "",
                    "type": 'string',
                    "format": '',
                    "bSortable": true

                },
                CONSTANT.DATA_TABLES.COLUMN.LASTMODIFYDATE

                , CONSTANT.DATA_TABLES.COLUMN.ACTIONBTN("GroupId", "/ORG/Group/Edit", [
                    {
                        name: "编辑",
                        data: "GroupId",
                        icon: "fa-paste",
                        url: "/ORG/Group/Edit",
                        cssClass: ""
                    },
                    {
                        name: "添加用户",
                        data: "GroupId",
                        icon: "fa-user",

                        cssClass: ""
                    },
                    {
                        name: "添加权限",
                        data: "GroupId",
                        icon: "fa-plus",

                        cssClass: ""
                    }
                ])

            ],
            /*
            * 向服务器传递的参数
            */
            "fnServerParams": function (data) {
                data.keyWord = $("form[datatable='tableGrid']").find("#keyWord").val();

            }
        });
    },
    Remote: function (target) {
        Notify.Remote({
            Title: "设置组",
            remote: "/ORG/Group/GroupTree?t=" + Math.random() + "&userid=" + target.attr("id"),
            buttons: [
                { id: "close", isClose: true, Name: "关闭" },
                {
                    id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                        var itemKeys = "";
                        itemKeys = Permission.GetNodeTree(modal, ".jstree");
                        Ajax({
                            url: BaseUrl + "/relationUser/relationUserSave",
                            data: { UserId: target.attr("id"), keys: itemKeys, relationType: 1 },
                            success: function (result) {
                                modal.modal("hide");
                            }
                        });
                    }
                }
            ],
            loaded: function (modal, id) {//初始化对象
                modal.find(".jstree").jstree({
                    "checkbox": {
                        "three_state": true,//父子级别级联选择
                        "tie_selection": true,
                        "keep_selected_style": false
                    },
                    "plugins": ["wholerow", "checkbox"]
                });
            }
        })
    }
}
var Page = {
    Init: function () {
        $.fn.CustomForm.TreeTable($("#tableGrid"), {
            expandable: true,
            indent: 20,//缩进
            initialState: "collapsed", //默认不展开
            stringCollapse: '关闭',
            stringExpand: '展开',
            column: 1,
            ajaxData: true,//是否初始化
            ajaxUrl: BaseUrl + "/page/forgrid",
            deleteUrl: BaseUrl + "/page/delete",//remove服务器连接
            ServerParams: function (data) {
                data.LocalName = $("form[datatable='tableGrid']").find("#LocalName").val();
                data.RouteUrl = $("form[datatable='tableGrid']").find("#RouteUrl").val();
                data.SortName = "OrderNum";
                data.SortOrder = "asc";
                return data;
            },
            ajaxSuccess: function (result, ischecked) {
                result = result.Rows;
                if (result && result.length > 0) {
                    var row = "";
                    for (var i = 0; i < result.length; i++) {
                        var children = false;
                        $(result).each(function (index, item) {
                            if (item.ParentId == result[i].PageId) {
                                children = true;
                                return false;
                            }
                        });
                        row += ' <tr  role="row" data-tt-id="' + result[i].PageId + '"  data-tt-branch="' + (children ? "true" : "false") + '" data-tt-parent-id="' + (result[i].ParentId ? result[i].ParentId : "0") + '">';
                        row += '<td>';
                        row += '<div class="i-checks checkItem">';
                        row += '    <label> <input type="checkbox" class="thead " value="' + result[i].PageId + '" ' + (ischecked ? "checked" : "") + ' /></label>';
                        row += '</div>';
                        row += ' </td >';
                        row += '<td style="text-align:left;">' + result[i].LocalName + '</td>';
                        row += ' <td>' + result[i].OrderNum + '</td>';
                        row += '<td>' + result[i].LastModifyDate + '</td>';
                        row += '<td>' + result[i].RouteUrl + '</td>';
                        row += ' <td><a class="btn btn-info  btn-rounded  btn-outline btn-circle" href="/admin/page/Edit?id=' + result[i].PageId + '" title="编辑"><i class="fa fa-paste"></i></a></td>';
                        row += '</tr >';
                    }
                    return row;

                }
                return "";
            },
            ajaxCompleted: function (result) {
                $("#tableGrid").find("tbody>tr[data-tt-parent-id!='0']").css("display", "none");
            }
        });


    },
    ShowPageAction: function (pageid) {//显示页面按钮
        var actionTable;
        Notify.Remote({
            Title: "页面按钮设置",
            remote: BaseUrl + "/pageaction/index?pageId=" + pageid + "&t=" + Math.random(),
            buttons: [{ id: "close", isClose: true, Name: "关闭" }],
            loaded: function (modal, id) {
                $("#actiontableGridForm").CustomForm({
                    isValidate: true,
                    isTable: false
                });

                $("#actiontableGridForm").find(".btn-save").on("click", function () {

                    if (!$("#actiontableGridForm").valid()) {
                        return false;
                    }
                    Ajax({
                        url: BaseUrl + "/pageAction/Edit",
                        data: { PageId: pageid, ActionName: $("#actiontableGridForm").find("input[name='ActionName']").val(), LocalName: $("#actiontableGridForm").find("input[name='LocalName']").val() },
                        success: function (result) {
                            Notify.Success("添加成功");
                            actionTable.fnPageChange(0);
                            // modal.modal("hide");
                        }
                    });

                });
                $("#actiontableGridForm").find(".btn-add-system").on("click", function () {
                    Page.ShowAction(pageid, actionTable);
                    //actionTable.fnPageChange(0);
                });
                actionTable = $("#actiontableGrid").CustomForm({
                    isValidate: false,
                    isTable: true,
                    //是否开启本地分页
                    //"paging": false,
                    deleteUrl: BaseUrl + "/pageaction/Delete",
                    ajaxUrl: BaseUrl + "/pageaction/forgrid",
                    // serverSide: false,
                    // 禁用原生搜索
                    searching: false,
                    "order": [[1, "desc"]], //默认排序
                    "columns": [
                        CONSTANT.DATA_TABLES.COLUMN.CHECKBOX("PageActionId", false, "", "5%")
                        , {
                            "mData": "ActionName",
                            "name": "ActionName",
                            "data": "ActionName",
                            "title": "标识",
                            "sDefaultContent": "",
                            "type": 'string',
                            "format": '',
                            "bSortable": false
                        }
                        , {
                            "mData": "LocalName",
                            "name": "LocalName",
                            "data": "LocalName",
                            "title": " 名称",
                            "sDefaultContent": "",
                            "type": 'string',
                            "format": '',
                            "bSortable": false

                        }],
                    "fnServerParams": function (data) {
                        data.PageId = pageid;

                    }
                });

            }

        });
    },
    ShowAction: function (pageid, actionTable) {//显示系统按钮
        var actionTable1;
        Notify.Remote({
            Title: "页面按钮设置",
            remote: BaseUrl + "/pageaction/List?pageId=" + pageid + "&t=" + Math.random(),
            buttons: [
                { id: "close", isClose: true, Name: "关闭" },
                {
                    id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                        var itemKeys = $("#actionGrid").TableSelectRow();

                        Ajax({
                            url: BaseUrl + "/pageaction/ActionSave",
                            data: { pageid: pageid, actionKeys: itemKeys },
                            success: function (result) {
                                actionTable.fnPageChange(0);
                                modal.modal("hide");
                            }
                        });
                        return false;
                    }
                }
            ],
            loaded: function (modal, id) {
                $("#actionGrid").CustomForm({
                    isValidate: true,
                    isTable: false
                });
                actionTable1 = $("#actionGrid").CustomForm({
                    isValidate: false,
                    isTable: true,
                    //是否开启本地分页
                    "paging": false,
                    serverSide: false,
                    ajax: null,
                    // 禁用原生搜索
                    searching: false,
                    "order": [[1, "desc"]], //默认排序
                    "columns": [
                        {
                            className: "td-checkbox",
                            orderable: false,
                            bSortable: false,
                            data: "ActionId",
                            "mData": "ActionId",
                            "sWidth": "5%"
                        }
                        , {
                            "mData": "ActionName",
                            "data": "ActionName",
                            "title": "标识",
                            "sDefaultContent": "",
                            "type": 'string',
                            "format": '',
                            "bSortable": false
                        }
                        , {
                            "mData": "LocalName",
                            "data": "LocalName",
                            "title": " 名称",
                            "sDefaultContent": "",
                            "type": 'string',
                            "format": '',
                            "bSortable": false

                        }]
                });

            }

        });
    }
}
//用户关系
var RelationUser = {
    ///删除用户关系 gridId 表示jquery 对象 relationType 表示类别 0 role 1 group 2部门 
    Remove: function (gridId, relationType, target, func) {
        var itemUsers = $(gridId).TableSelectRow();
        if (!itemUsers || itemUsers == "") {
            Notify.Error("请选择要删除的用户");
            return false;
        }
        Notify.Confirm("您确定要移除该用户吗", "确认提示", function () {
            Ajax({
                url: BaseUrl + "/relationUser/RemoveRlUser",
                data: { resourceId: target.attr("id"), relationType: relationType, itemKeys: itemUsers },
                success: function (result) {
                    Notify.Success("删除成功");
                    if (func)
                        func();

                    // modal.modal("hide");
                }
            });
            return true;
        });

    },
    Add: function (gridId, relationType, target, func) {
        var itemUsers = $(gridId).TableSelectRow();

        if (!itemUsers || itemUsers == "") {
            Notify.Error("请选择要添加的用户");
            return false;
        }
        Ajax({
            url: BaseUrl + "/relationUser/AddRlUser",
            data: { resourceId: target.attr("id"), relationType: relationType, itemKeys: itemUsers },
            success: function (result) {
                Notify.Success("添加成功");
                if (func)
                    func();

                // modal.modal("hide");
            }
        });
    }
}
var Permission = {
    //获取选中的权限 modal 容器
    //className jstree属性值用于查找jstree
    //获取的属性名
    GetNodeTree: function (modal, className, attrName) {
        var nodes = modal.find(className).jstree().get_selected(true);
        var itemKeys = "";
        var index = 0;
        for (var i = 0; i < nodes.length; i++) {
            if (index > 0) {
                itemKeys += ",";
            }
            if (!attrName || attrName == "") {
                if (nodes[i].state.id) {
                    itemKeys += nodes[i].state.id;
                    index++;
                }
            }
            else {
                if (nodes[i].state[attrName]) {
                    itemKeys += nodes[i].state[attrName];
                    index++;
                }
            }
        }
        return itemKeys;

    },
    //modal加载权限或者角色对象
    //target jquery html 按钮对象 
    //eventType 事件元素序号
    //title 模态对话框标题
    //url 模态对话框路径
    //resourceType 权限关系类别 0 role 1:person

    Remote: function (target, resourceType) {
        Notify.Remote({
            Title: "设置权限",
            remote: BaseUrl + "/page/pageTree?t=" + Math.random() + "&resourceid=" + target.attr("id") + "&resourceType=" + resourceType,
            buttons: [
                { id: "close", isClose: true, Name: "关闭" },
                {
                    id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                        var permissions = Permission.GetNodeTree(modal, ".permission");
                        var unpermission = Permission.GetNodeTree(modal, ".unpermission");
                        Ajax({
                            url: BaseUrl + "/permission/PermissionSave",
                            data: { resourceId: target.attr("id"), resourceType: resourceType, permissions: permissions, unpermissions: unpermission },
                            success: function (result) {
                                modal.modal("hide");
                            }
                        });
                        return false;
                    }
                }
            ],
            loaded: function (modal, id) {//初始化对象
                modal.find(".permission").jstree({
                    "checkbox": {
                        "three_state": true,//父子级别级联选择
                        "tie_selection": true,
                        "keep_selected_style": false,
                        "check_permission": true//是否权限加载
                    },
                    "plugins": ["wholerow", "checkbox"]
                });
                modal.find(".unpermission").jstree({
                    "checkbox": {
                        "three_state": false,//父子级别级联选择
                        "tie_selection": true,
                        "keep_selected_style": false,
                        "check_permission": false//是否权限加载
                    },
                    "plugins": ["wholerow", "checkbox"]
                });
            }
        })
    }
}
